package com.app.controller;

import cn.hutool.core.util.StrUtil;
import com.app.common.Result;
import com.app.common.SystemConstant;
import com.app.model.*;
import com.app.server.*;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.AnimalRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 野生动物记录
 */
@Slf4j
@RestController
@RequestMapping("/sbbz/animalRecord")
public class AnimalRecordController {

    @Autowired
    private AnimalRecordService animalRecordService;
    @Autowired
    private UserService userService;

    @Autowired
    private RecordFileService recordFileService;


    // 查询列表
    @GetMapping("/getAnimalRecordList")
    public Result getAnimalRecordList(@RequestParam(defaultValue = "0") Integer page,
                                      @RequestParam(defaultValue = "10") Integer limit, String keyword) {
        AnimalRecordVo animalRecordVo = animalRecordService.getAnimalRecordList(page, limit, keyword);
        return Result.success(animalRecordVo);
    }

    //根据id查询详情
    @GetMapping("/getRecordById")
    public Result getRecordById(Integer id) {
        AnimalRecordModel animalRecord = animalRecordService.getById(id);
        String fileIdArr = animalRecord.getFileId();
        String[] split = fileIdArr.split(",");
        StringBuffer sb = new StringBuffer();
        StringBuffer sb1 = new StringBuffer();
        for (String fileIds : split) {
            int fileId = Integer.parseInt(fileIds);
            RecordFileModel recordFile = recordFileService.getById(fileId);
            if (recordFile != null) {
                if (recordFile.getFileType() != null && recordFile.getFileType() == 1) {
                    sb.append(recordFile.getUrl()).append(",");
                }
                if (recordFile.getFileType() != null &&recordFile.getFileType() == 2) {
                    sb1.append(recordFile.getUrl()).append(",");
                }
            }
        }
        if (sb.length() > 0) {
            String updatedNumbers = sb.substring(0, sb.toString().length() - 1);
            animalRecord.setUrl(updatedNumbers);
        }
        if (sb1.length() > 0) {
            String updatedNumbers1 = sb1.substring(0, sb1.toString().length() - 1);
            animalRecord.setVideoUrl(updatedNumbers1);
        }
        return Result.success(animalRecord);
    }

    //查询用户野生动物记录列表
    @GetMapping("/getUserRecordList")
    public Result getUserRecordList(Integer page, Integer limit, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AnimalRecordVo animalRecordList = animalRecordService.getUserRecordList(page, limit, user.getOpenId());
        return Result.success(animalRecordList);
    }

    //查询用户野生动物详情记录
    @GetMapping("/getUserRecordById")
    public Result getUserRecordById(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AnimalRecordModel userRecord = animalRecordService.getById(id);
        String fileIdArr = userRecord.getFileId();
        String[] split = fileIdArr.split(",");
        for (String fileIds : split) {
            int fileId = Integer.parseInt(fileIds);
            RecordFileModel recordFile = recordFileService.getById(fileId);
            if (recordFile != null) {
                if (recordFile.getFileType() != null && recordFile.getFileType() == 1) {
                    userRecord.setUrl(recordFile.getUrl());
                }
                if (recordFile.getFileType() != null &&recordFile.getFileType() == 2) {
                    userRecord.setVideoUrl(recordFile.getUrl());
                }
            }
        }
        return Result.success(userRecord);
    }


    //用户新增和修改记录
    @PostMapping("/addAndUpdateRecord2")
    public Result addAndUpdateRecord2(@RequestBody AnimalRecordModel animalRecordModel, HttpServletRequest request) {
        AnimalRecordModel animalRecord = animalRecordService.getById(animalRecordModel.getId());
        if (animalRecord != null) {
            animalRecordModel.setUpdateTime(CommonHelp.getNowTimestamp());
            animalRecordService.updateById(animalRecordModel);
            return Result.success("修改成功");
        } else {
            animalRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
            animalRecordService.save(animalRecordModel);


            String fileId = animalRecordModel.getFileId();
            String[] split = fileId.split(",");
            List<Integer> list = new ArrayList<>();
            for (String s : split) {
                int fileIds = Integer.parseInt(s);
                list.add(fileIds);
            }
            List<RecordFileModel> recordFileModels = recordFileService.listByIds(list);
            return Result.success(recordFileModels);
        }
    }


    //用户新增和修改记录
    @PostMapping("/addAndUpdateRecord")
    public Result addAndUpdateRecord(@RequestBody AnimalRecordModel animalRecordModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (StrUtil.isBlank(user.getAreaId())) {
            return Result.error(407, "请先完善个人信息");
        }
        if (animalRecordModel.getId() != null && animalRecordModel.getId() != 0) {
            animalRecordModel.setUpdateTime(CommonHelp.getNowTimestamp());
            animalRecordService.updateById(animalRecordModel);
        } else {
            animalRecordModel.setUsername(user.getName());
            animalRecordModel.setOpenId(user.getOpenId());
            animalRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
            StringBuilder s1 = new StringBuilder();
            if (animalRecordModel.getPic() != null && animalRecordModel.getPic().length > 0) {
                String[] pic = animalRecordModel.getPic();
                for (int i = 0; i < pic.length; i++) {
                    String[] split = pic[i].split("/");
                    int length = split.length;
                    RecordFileModel recordFileModel = new RecordFileModel();
                    recordFileModel.setName(split[length - 1]);
                    recordFileModel.setUrl(pic[i]);
                    recordFileModel.setFileType(1);
                    recordFileModel.setCreateTime(CommonHelp.getNowTimestamp());
                    recordFileService.insert(recordFileModel);
                    s1.append(recordFileModel.getId()).append(",");
                }
            }
            if (animalRecordModel.getVideo() != null && animalRecordModel.getVideo().length > 0) {
                String[] pic = animalRecordModel.getVideo();
                for (int i = 0; i < pic.length; i++) {
                    String[] split = pic[i].split("/");
                    int length = split.length;
                    RecordFileModel recordFileModel = new RecordFileModel();
                    recordFileModel.setName(split[length - 1]);
                    recordFileModel.setUrl(pic[i]);
                    recordFileModel.setFileType(2);
                    recordFileModel.setCreateTime(CommonHelp.getNowTimestamp());
                    recordFileService.insert(recordFileModel);
                    if (i == pic.length - 1) {
                        s1.append(recordFileModel.getId());
                    } else {
                        s1.append(recordFileModel.getId()).append(",");
                    }
                }
            }
            animalRecordModel.setFileId(s1.toString());
            animalRecordService.save(animalRecordModel);
        }
        return Result.success("操作成功");
    }

    //根据id删除动物记录，并且从硬盘把动物记录的文件内容也删了
    @GetMapping("/delAnimalRecord")
    public Result delAnimalRecord(Integer id) {
        AnimalRecordModel animalRecord = animalRecordService.getById(id);
        String fileIdList = animalRecord.getFileId();
        String[] fileIdArr = fileIdList.split(",");
        for (String fileIds : fileIdArr) {
            int fileId = Integer.parseInt(fileIds);
            RecordFileModel recordFile = recordFileService.getById(fileId);
            try {
                File file1 = new File(SystemConstant.DEFAULT_UPLOAD_URL + recordFile.getName());
                if (file1.delete()) {
                    System.out.println(file1.getName() + " 图片已被删除！");
                } else {
                    System.out.println("删除图片操作失败！");
                }
            } catch (Exception e) {
                return Result.success(e);
            }
            recordFileService.removeById(fileId);
        }
        animalRecordService.removeById(id);
        return Result.success("删除成功");
    }
}
